package com.zyy.game.tianlong.network.codec;

import com.zyy.game.tianlong.network.SocketMsg;
import com.zyy.game.tianlong.network.exception.ApiException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.EncoderException;

import java.nio.charset.StandardCharsets;

/**
 * 编码器 将{@link SocketMsg}对象转换为指定长度协议的二进制
 *
 * @author relufi
 * @date 2019/7/22 0022 10:24
 */
@ChannelHandler.Sharable
public class GameMsgToByteEncoder extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
        ByteBuf buf = null;
        try {
            if (msg instanceof SocketMsg) {
                SocketMsg socketMsg = (SocketMsg) msg;
                String data = socketMsg.getData();
                byte[] bytes;
                if(data == null) {
                    bytes = new byte[0];
                }else {
                    bytes = data.getBytes(StandardCharsets.UTF_8);
                }
                buf = ctx.alloc().ioBuffer(bytes.length + 12);
                buf.writeIntLE(bytes.length + 8);
                buf.writeIntLE(socketMsg.getOpCode());
                buf.writeIntLE(socketMsg.getSubCode());
                buf.writeBytes(bytes);
                ctx.write(buf, promise);
                buf = null;
            } else {
                throw new ApiException("write数据格式错误");
            }
        } catch (Throwable e) {
            throw new EncoderException(e);
        } finally {
            if (buf != null) {
                buf.release();
            }
        }
    }
}
